﻿using System;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Input;

using xEngine.Rendering;
using xEngine.Utils;
using xEngine.Debugging;

namespace xEngine.UI.Screens
{
    public class ScreenSplashVideo : Screen
    {
        #region Member Variables

        private bool _stretch;
        private String _vid;
        private Video _video;
        private VideoPlayer _player;

        #endregion

        #region Properties
        #endregion

        #region Constructors

        public ScreenSplashVideo(String video, bool stretch, float vol, Keys? skipBtn) : base(skipBtn)
        {
            _vid = video;
            _stretch = stretch;
            _player = new VideoPlayer();
            _player.Volume = vol;

            ProcessMouse = false;
        }

        #endregion

        #region Functions

        public override void LoadContent()
        {
            base.LoadContent();

            _video = ScreenManager.Game.Content.Load<Video>(_vid);
            _player.Play(_video);
            _player.Pause();
        }
        public override void UnloadContent()
        {
            _player.Stop();
        }
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            if (_player.State == MediaState.Paused && State != ScreenState.FadeOut)
                _player.Resume();

            if(_player.State == MediaState.Stopped || _video.Duration.TotalSeconds - _player.PlayPosition.TotalSeconds <= FadeTimeout)
                FadeOut();
        }
        public override void Render(GameTime gameTime)
        {
            Texture2D frame = _player.GetTexture();       

            Rectangle dest;

            if(_stretch)
                dest = new Rectangle(0, 0, ScreenManager.GraphicsDevice.Viewport.Width, ScreenManager.GraphicsDevice.Viewport.Height);
            else
                dest = new Rectangle((ScreenManager.GraphicsDevice.Viewport.Width - frame.Width) / 2, (ScreenManager.GraphicsDevice.Viewport.Height - frame.Height) / 2, frame.Width, frame.Height);

            ScreenManager.SpriteBatch.Begin();
            ScreenManager.SpriteBatch.Draw(frame, dest, Color.White);
            ScreenManager.SpriteBatch.End();

            base.Render(gameTime);
        }

        public override void FadeOut()
        {
            _player.Stop();

            base.FadeOut();
        }

        #endregion
    }
}
